<?php
/**
 * Created by PhpStorm.
 * User: Jerry
 * Date: 2016/12/17
 * Time: 11:42
 */

namespace SDXApi\Service;


/**
 * Class SeminarService
 * @package SDXApi\Service
 */
use SDXApi\Model\SeminarTemplateCategoryGoodsModel;
use SDXApi\Repositories\GoodsRepository;

/**
 * Class SeminarService
 * @package SDXApi\Service
 */
class SeminarService
{
	/**
	 * @var \Model|\Think\Model
	 */
	protected static $seminarModel;

	/**
	 * @var \Model|\Think\Model
	 */
	protected static $seminarPageModel;

	/**
	 * @var
	 */
	protected $user_id;

	/**
	 * @var
	 */
	protected $goodsInfo;

	/**
	 * @var
	 */
	protected $wid;

	/**
	 * @var GoodsRepository
	 */
	protected static $goodsRepository;

	/**
	 * @var
	 */
	protected static $SeminarBagModel;

	/**
	 * @var
	 */
	protected static $SeminarCategoryGoodsModel;

	/**
	 * @var
	 */
	protected static $UserModel;

	/**
	 * @var \Model|\Think\Model
	 */
	protected static $SeminarGoodsModel;

	/**
	 * @var \Model|\Think\Model
	 */
	protected static $SeminarPageSeminarModel;

	/**
	 * @var
	 */
	protected static $SeminarPageTitleModel;

	/**
	 * @var
	 */
	protected $is_show;

	/**
	 * @var
	 */
	public $pageSize;

	/**
	 * @var
	 */
	public $pageNumber;

	/**
	 * @var
	 */
	public $is_app;

	/**
	 * @var
	 */
	public $version;

	/**
	 * 注入实例
	 * SeminarService constructor.
	 * @param $user_id
	 * @param $wid
	 */
	public function __construct($user_id = 0, $wid = 0)
	{
		self::$seminarModel = D('Seminar');
		self::$seminarPageModel = D('SeminarPage');
		self::$goodsRepository = new GoodsRepository($user_id, $wid);
		self::$SeminarBagModel = D('SeminarTemplateBag');
		self::$SeminarCategoryGoodsModel = D('SeminarTemplateCategoryGoods');
		self::$UserModel = D('Users');
		self::$SeminarGoodsModel = D('SeminarTemplatePageGoods');
		self::$SeminarPageSeminarModel = D('SeminarPageSeminar');
		self::$SeminarPageTitleModel = D('SeminarTemplatePageTitle');

		$this->user_id = empty($user_id) ? 0 : $user_id;
		$this->wid = $wid;
	}

	/**
	 * Created by Jerry
	 * @param $name
	 * @param $value
	 */
	public function __set($name, $value)
	{
		$this->$name = $value;
	}

	/**
	 * Created by Jerry
	 * @return $this
	 */
	protected function findSeminarTemplates()
	{
		return self::$seminarModel->find_seminar_templates();
	}


	/**
	 * 查找指定专题名称下的模版并返回
	 * Created by Jerry
	 * @param $name
	 * @return bool
	 */
	public function findSeminarTemplatePageByName($name)
	{
		$template = $this->findSeminarTemplateByName($name);

		$page = $this->findSeminarPagesByTemplateId($template['id']);

		if (empty($page)) {
			return '';
		}

		return $this->checkSeminarTemplatePages($page);
	}

	/**
	 * 查找指定专题id下的模版并返回
	 * Created by Jerry
	 * @param $id
	 * @return array|string
	 */
	public function findSeminarTemplatePageById($id)
	{

//		if ($temp = $this->getSeminarTemplatePageCache($id)) {
//			return $temp;
//		}

		$template = $this->findSeminarTemplateById($id);
		$page = $this->findSeminarPagesByTemplateId($template['id']);

		if (empty($page)) {
			return '';
		}

		$data = $this->checkSeminarTemplatePages($page);

//		$this->setSeminarTemplatePageCache($id, $data);

		return $data;
	}


	/**
	 * Created by Jerry
	 * @param $id
	 * @return bool|mixed
	 */
	protected function getSeminarTemplatePageCache($id)
	{
		$userRank = $this->getUserRank();

//		$hashName = hash('md5', 'seminar_template_page_' . $id . '_' . $userRank);
		$hashName = 'seminar_template_page_' . $id . '_' . $userRank;
		$data = S($hashName);

		if (empty($data)) {
			return false;
		}

		return $data;
	}

	/**
	 * Created by Jerry
	 * @param $id
	 * @param $data
	 */
	protected function setSeminarTemplatePageCache($id, $data)
	{
		$userRank = $this->getUserRank();

//		$hashName = hash('md5', 'seminar_template_page_' . $id . '_' . $userRank);
		$hashName = 'seminar_template_page_' . $id . '_' . $userRank;
		S($hashName, $data, 3600);
	}

	/**
	 * Created by Jerry
	 * @param $id
	 * @return mixed
	 */
	public function getTemplateById($id)
	{
		return $this->findSeminarTemplateById($id);
	}

	/**
	 * 缓存所有专题
	 * Created by Jerry
	 * @return bool
	 */
	public function seminarTemplateCache()
	{
		$seminarList = self::$seminarModel->findSeminarListByStatus();

		if (empty($seminarList)) {
			return false;
		}

		return $this->cacheSeminarData($seminarList);
	}

	/**
	 * 处理缓存数据
	 * Created by Jerry
	 * @param $seminarList
	 * @return bool
	 */
	protected function cacheSeminarData($seminarList)
	{
		$visitor = self::$UserModel->findUserByUserRank(1);
		$vip = self::$UserModel->findUserByUserRank(2);

		foreach ($seminarList as $key => $value) {

			$rank1 = S('seminar_template_page_data_' . $value['id'] . '_' . 1);
			$rank2 = S('seminar_template_page_data_' . $value['id'] . '_' . 2);

			if (empty($rank1)) {
				$data = array();

				$this->user_id = $visitor['user_id'];
				$this->wid = 8;
				self::$goodsRepository->userId = $visitor['user_id'];
				$template = $this->getTemplateById($value['id']);

				if (empty($template)) {
					continue;
				}

				$data['seminar_name'] = $template['name'];
				$data['desc'] = $template['desc'];
				$data['seminar_list'] = $this->findSeminarTemplatePageById($value['id']);
				$cacheTime = mt_rand(3600, 4300);

				S('seminar_template_page_data_' . $value['id'] . '_' . 1, $data, $cacheTime);
			}

			if (empty($rank2)) {
				$data = array();

				$this->user_id = $vip['user_id'];
				$this->wid = 8;
				self::$goodsRepository->userId = $vip['user_id'];
				$template = $this->getTemplateById($value['id']);

				if (empty($template)) {
					continue;
				}

				$data['seminar_name'] = $template['name'];
				$data['desc'] = $template['desc'];
				$data['seminar_list'] = $this->findSeminarTemplatePageById($value['id']);
				$cacheTime = mt_rand(3600, 4300);

				S('seminar_template_page_data_' . $value['id'] . '_' . 2, $data, $cacheTime);
			}

		}

		return true;
	}

	/**
	 * 查找专题模版
	 * Created by Jerry
	 * @param $name
	 * @return $this
	 */
	protected function findSeminarTemplateByName($name)
	{
		return self::$seminarModel->find_seminar_template_by_name($name);
	}

	/**
	 * 查找指定id模版
	 * Created by Jerry
	 * @param $id
	 */
	protected function findSeminarTemplateById($id)
	{
		return self::$seminarModel->find_seminar_template_by_id($id, $this->is_show);
	}

	/**
	 * 查找指定专题下的模版页面
	 * Created by Jerry
	 * @param $id
	 * @return $this
	 */
	protected function findSeminarPagesByTemplateId($id)
	{
		return self::$seminarPageModel->find_seminar_template_pages_by_template_id($id);
	}

	/**
	 * Created by Jerry
	 * @return int
	 */
	protected function getUserRank()
	{

		$rank = self::$UserModel->get_user_rank($this->user_id);

		if (empty($rank)) {
			return -1;
		}

		return $rank['user_rank'];
	}

	/**
	 * 处理页面数据
	 * Created by Jerry
	 * @param $pages
	 * @return array
	 */
	protected function checkSeminarTemplatePages($pages)
	{
		$data = array();
		foreach ($pages as $key => $value) {
			$seminar = $this->checkSeminarTemplatePageType($value);

			if (empty($seminar)) {
				continue;
			}

			$seminar['border_size'] = 20;

			$data[] = $seminar;
		}

		if (empty($data)) {
			$data = array();
		}

		return $data;
	}

	/**
	 * 处理各类型数据
	 * Created by Jerry
	 * @param $page
	 * @return bool
	 */
	protected function checkSeminarTemplatePageType($page)
	{
		if (empty($page)) {
			return false;
		}

		$data = array();
		switch ($page['type'])
		{
			case 1:
				$data = $this->checkPageFont($page);
				break;
			case 2:
				$data = self::checkPageImage($page);
				break;
			case  3:
				$data = $this->checkPageGoods($page);
				break;
			case 4:
				$data = self::checkBag($page);
				break;
			case 5:
				$data = $this->categoryGoods($page);
				break;
			case 6:
				$data = $this->checkSeminar($page);
				break;
			case 7:
				$data = $this->checkTitle($page);
				break;
			case 8:
				$data = $this->checkAlbum($page);
				break;

			default:
				return false;
				break;
		}

		return $data;
	}

	/**
	 * 专辑处理
	 * Created by Jerry
	 * @param array $page
	 * @return array
	 */
	protected function checkAlbum($page = array())
	{
		$data = self::$seminarPageModel->find_seminar_template_album_by_template_id($page['id']);

		$albums = $this->getAlbumCover($data);

		$page['album_list'] = $albums;

		if (empty($albums)) {
			$page['album_list'] = array();
		}

		unset($page['font_type'], $page['font_size'], $page['font_content'], $page['font_link'], $page['image_url'], $page['image_link'], $page['image_size'], $page['goods_type'], $page['goods_id'], $page['template_id']);

		return $page;
	}

	/**
	 * Created by Jerry
	 * @param array $albums
	 * @return array|bool
	 */
	protected function getAlbumCover($albums = array())
	{
		if (empty($albums)) {
			return false;
		}

		$albumService = new AlbumService();

		foreach ($albums as $key => $value) {
			$cover = $albumService->getAlbumCover($value['id']);

			if ($cover) {
				$albums[$key]['cover'] = $cover;
			}

		}

		return $albums;
	}

	/**
	 * 返回标题数据
	 * Created by Jerry
	 * @param $page
	 * @return mixed
	 */
	protected function checkTitle($page)
	{
		$title = self::$SeminarPageTitleModel->findSeminarPageTitleByPageId($page['id']);

		if (empty($title)) {
			$title = array();
		}

		$page['title'] = $title;
		unset($page['font_type'], $page['font_size'], $page['font_content'], $page['font_link'], $page['image_url'], $page['image_link'], $page['image_size'], $page['template_id'], $page['goods_type'], $page['goods_id']);
		return $page;
	}

	/**
	 * Created by Jerry
	 * @param $page
	 * @return mixed
	 */
	protected function checkSeminar($page)
	{
		$seminarList = self::$SeminarPageSeminarModel->findSeminarPageSeminarByPageId($page['id']);

		if (empty($seminarList)) {
			$seminarList = array();
		}

		$page['seminar_list'] = $seminarList;

		unset($page['font_type'], $page['font_size'], $page['font_content'], $page['font_link'], $page['image_url'], $page['image_link'], $page['image_size'], $page['template_id'], $page['goods_type'], $page['goods_id']);

		return $page;
	}

	/**
	 * Created by Jerry
	 * @param $page
	 * @return bool|array
	 */
	protected function categoryGoods($page)
	{
		if (empty($page)) {
			return false;
		}

		$categoryInfo = self::findCategoryByStencilId($page['id']);

		$goods = $this->checkGoodsCategory($categoryInfo);

		if (empty($goods)) {
			$goods = array();
		}

//		$chunkGoods = array_chunk($goods, $this->pageSize);
//
//		$goodsCount = count($goods);
//
//		$goodsPage = $this->pageCategory($goodsCount);
//
//		$this->pageNumber -= 1;
//		if ($this->pageNumber <= 1) {
//			$this->pageNumber = 0;
//		}
//
//		if (empty($chunkGoods[$this->pageNumber])) {
//			$chunkGoods[$this->pageNumber] = array();
//		}
//
//		$page['goods_list'] = $chunkGoods[$this->pageNumber];
//		$page['page'] = $goodsPage;

		$page['goods_list'] = $goods;
		$page['type'] = 3;
		unset($page['goods_id']);



		unset($page['font_type'], $page['font_size'], $page['font_content'], $page['font_link'], $page['image_url'], $page['image_link'], $page['image_size'], $page['template_id']);

		return $page;
	}

	/**
	 * Created by Jerry
	 * @param $goodsCount
	 * @return array|bool
	 */
	protected function pageCategory($goodsCount)
	{
		$goodsPageCountNumber = ceil($goodsCount / $this->pageSize);
		$firstPage = $this->pageSize * ($this->pageNumber - 1);

		if ($this->pageNumber > $goodsCount) {
			$this->pageNumber = 1;
			return false;
		}

		$pageData = array(
			'pagecount'	=>	$goodsPageCountNumber,
			'firstpage'	=>	$firstPage,
			'pagesize'	=>	$this->pageSize,
		);

		return $pageData;
	}

	/**
	 * Created by Jerry
	 * @param $id
	 * @return bool
	 */
	protected static function findCategoryByStencilId($id)
	{
		if (empty($id)) {
			return false;
		}

		return self::$SeminarCategoryGoodsModel->findCategoryByTemplateId($id);
	}

	/**
	 * 处理分类商品
	 * Created by Jerry
	 * @param $category
	 * @return array|mixed
	 */
	protected function checkGoodsCategory($category)
	{

		$goods = $this->findCategoryGoodsByCategoryId($category['category_id'], $category['goods_where'], $this->wid);
		$goodsList = self::$goodsRepository->formatGoodsTransform($goods);

		foreach ($goodsList as $key => $value) {
			$goodsList[$key]['id'] = $value['goods_id'];
		}

		if (count($goodsList) > 1) {
			$goodsList = self::checkDataSort($goodsList);
		}

		$goodsList = array_merge($goodsList);

		return $goodsList;
	}

	/**
	 * Created by Jerry
	 * @param $category_id
	 * @param $goods_where
	 * @param $wid
	 * @return bool|mixed
	 */
	protected function findCategoryGoodsByCategoryId($category_id, $goods_where, $wid)
	{
		return self::$goodsRepository->findCategoryGoodsByCategoryId($category_id, $goods_where, $wid);
	}


	/**
	 * 处理红包类型
	 * Created by Jerry
	 * @param $page
	 * @return bool|array
	 */
	static protected function checkBag($page)
	{
		$bagData = self::$SeminarBagModel->get_seminar_template_bag_by_id($page['id']);

		if (empty($bagData)) {
			return false;
		}

		$page['image_start'] 	= $bagData['image_start'];
		$page['image_end'] 		= $bagData['image_end'];
		$page['bag_link'] 		= $bagData['bag_link'];
		$page['bag_id']			= $bagData['bag_id'];

		$page['bag_size']		= '750 * 900';

		unset($page['font_type'], $page['font_size'], $page['font_content'], $page['font_link'], $page['image_url'], $page['image_link'], $page['image_size'], $page['goods_type'], $page['goods_id'], $page['template_id']);

		return $page;
	}

	/**
	 * 处理字体内容
	 * Created by Jerry
	 * @param $page
	 * @return mixed
	 */
	protected function checkPageFont($page)
	{
		unset($page['image_url'], $page['image_link'], $page['image_size'], $page['goods_type'], $page['goods_id'], $page['template_id']);

		if ($page['font_type'] >= 7 && $this->version <= '47' && $this->is_app) {
			return false;
		}

		return $page;
	}


	/**
	 * 处理图片数据
	 * Created by Jerry
	 * @param $page
	 * @return mixed
	 */
	static protected function checkPageImage($page)
	{
		unset($page['font_type'], $page['font_size'], $page['font_content'], $page['font_link'], $page['goods_type'], $page['goods_id'], $page['template_id']);

//		旧版地址替换
		$page['image_url'] = self::checkImageUrlReplace($page['image_url']);

		$page['image_size_data'] = self::imageTypeSize($page);

		return $page;
	}

	/**
	 * Created by Jerry
	 * @param $url
	 * @return mixed
	 */
	static protected function checkImageUrlReplace($url)
	{

		$urlPos = strpos($url, '//oss.shidexian.com');
		if ($urlPos !== false) {
			$url = str_replace('//oss.', 'https://image.', $url);
		}

		return $url;
	}

	/**
	 * Created by Jerry
	 * @param $image
	 * @return mixed
	 */
	static protected function imageTypeSize($image)
	{
		$imageSize = array(
			1	=>	'750px 360px',
			2	=>	'750px 1100px',
			3	=>	'710px 360px',
			4	=>	'750px 750px',
			5	=>	'750px 176px',
			6	=>	'750px 360px',
			7	=>	'750px 250px',
			8	=>	'750px 900px',
			9	=>	'750px 100px',
			10	=>	'750px 550px',
			11	=>	'750px 50px',
		);

		return $imageSize[$image['image_size']];
	}

	/**
	 * 处理商品数据
	 * Created by Jerry
	 * @param $page
	 * @return mixed
	 */
	protected function checkPageGoods($page)
	{
		unset($page['font_type'], $page['font_size'], $page['font_content'], $page['font_link'], $page['image_url'], $page['image_link'], $page['image_size'], $page['template_id']);

		$goods = $this->findSeminarGoodsByPageId($page['id']);

		$data = self::$goodsRepository->formatGoodsTransform($goods);

		foreach ($data as $key => $value) {
			$data[$key]['id'] = $value['goods_id'];
		}

		$data = array_merge($data);

		if (count($data) > 1) {
			$data = self::checkGoodsDataSort($data);
		}

		if (empty($data)) {
			return false;
		}


		$page['goods_list'] = $data;
		unset($page['goods_id']);

		return $page;
	}

	/**
	 * 获取专题商品
	 * Created by Jerry
	 * @param $page_id
	 * @return bool
	 */
	protected function findSeminarGoodsByPageId($page_id)
	{
		if (empty($page_id)) {
			return false;
		}

		return self::$SeminarGoodsModel->findSeminarTemplateGoodsByPageId($page_id, $this->wid);
	}


	/**
	 * 排序
	 * Created by Jerry
	 * @param $data
	 * @param string $field
	 * @return mixed
	 */
	static protected function checkDataSort($data, $field = 'sort')
	{
		$sort = array();
		foreach ($data as $key => $value) {
			$sort[] = $value[$field];
		}

		array_multisort($sort, SORT_DESC, $data);

		return $data;
	}

	/**
	 * Created by Jerry
	 * @param $data
	 * @return mixed
	 */
	static protected function checkGoodsDataSort($data)
	{
//		$sort = array();
//		foreach ($data as $key => $value) {
//			$sort['sort'][] = $value['sort'];
//			$sort['goods_number'][] = $value['goods_number'];
//
//		}
//
//		array_multisort($sort['goods_number'], SORT_NUMERIC, SORT_DESC, $sort['sort'], SORT_NUMERIC, SORT_DESC, $data);

		$sort = array();
		foreach ($data as $key => $value) {
			if (empty($value['goods_number'])) {
				$sort[] = $value['goods_number'];
			}
			else{
				$sort[] = $value['sort'];
			}
		}

		array_multisort($sort, SORT_NUMERIC, SORT_DESC, $data);

		return $data;
	}

	/**
	 * 二维数组去重
	 * Created by Jerry
	 * @param $arr
	 * @param $key
	 * @return mixed
	 */
	static protected function assoc_unique($arr, $key) {
		$tmp_arr = array();

		foreach ($arr as $k => $v) {
			if (in_array($v[$key], $tmp_arr)) {
				unset($arr[$k]);
			} else {
				$tmp_arr[] = $v[$key];
			}
		}

		return $arr;
	}


	/**
	 * 获取指定商品id所参加的专题
	 * Created by Jerry
	 * @param $goods_id
	 * @return array
	 */
	public function getSeminarGoodsListByGoodsId($goods_id)
	{

		$seminarGoodsList = $this->getSeminarGoodsByGoodsId($goods_id);

		if (empty($seminarGoodsList)) {
			$seminarGoodsList = array();
		}

		$seminarCategoryGoods = $this->getSeminarCategoryGoodsByGoodsId($goods_id);

		if (empty($seminarCategoryGoods)) {
			$seminarCategoryGoods = array();
		}

		$seminarList = array_merge($seminarGoodsList, $seminarCategoryGoods);

//		排重
		$seminarList = self::assoc_unique($seminarList, 'name');
//		排序
		$seminarList = self::checkDataSort($seminarList, 'id');
//		筛选1个
		$arr = array_chunk($seminarList, 1);
		$seminarList = $arr[0];

		return $seminarList;
	}

	/**
	 * Created by Jerry
	 * @param $goods_id
	 * @return mixed
	 */
	protected function getSeminarGoodsByGoodsId($goods_id)
	{
		$goods = self::$SeminarGoodsModel->findSeminarTemplateGoodsListByGoodsId($goods_id);
		return $goods;
	}

	/**
	 * Created by Jerry
	 * @param $goods_id
	 * @return array|bool
	 */
	protected function getSeminarCategoryGoodsByGoodsId($goods_id)
	{
//		查询商品分类id
		$goodsInfo = self::$SeminarCategoryGoodsModel->findGoodsByGoodsId($goods_id);

//		分类模版
		$categoryList = self::$SeminarCategoryGoodsModel->findSeminarTemplateCategoryByCategoryId($goodsInfo['cat_id']);

		return $this->checkCategoryListForGoodsId($categoryList, $goods_id);

	}

	/**
	 * Created by Jerry
	 * @param $categoryList
	 * @param $goods_id
	 * @return array|bool
	 */
	protected function checkCategoryListForGoodsId($categoryList, $goods_id)
	{
		if (empty($categoryList)) {
			return false;
		}

		$seminar = array();
		foreach ($categoryList as $key => $value) {
			$goods = $this->getSeminarGoodsByCategoryIdGoodsId($value, $goods_id);

			if ($goods === false) {
				continue;
			}
			unset($value['category_id'], $value['goods_where']);
			$seminar[] = $value;
		}

		return $seminar;
	}

	/**
	 * Created by Jerry
	 * @param $data
	 * @param $goods_id
	 * @return bool
	 */
	protected function getSeminarGoodsByCategoryIdGoodsId($data, $goods_id)
	{
		$seminar = self::$SeminarCategoryGoodsModel->findCategoryGoodsByCategoryId($data['category_id'], $data['goods_where']);

		foreach ($seminar as $key => $value) {
			if ($value['goods_id'] != $goods_id) {
				continue;
			}

			return true;
		}

		return false;
	}


}